package com.b2b.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;

import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.b2b.config.AlipayConfig;
import com.b2b.model.WalletDto;
import com.b2b.model.common.OrderPay;
import com.b2b.model.common.ResponseBean;
import com.b2b.model.entity.Orders;
import com.b2b.model.entity.Wallet;
import com.b2b.model.receive.WalletPay;
import com.b2b.service.AlipayService;
import com.b2b.service.OrdersService;
import com.b2b.service.WalletService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/payment")
@PropertySource("classpath:config.properties")
public class PaymentController {

    @Value("${refreshTokenExpireTime}")
    private String refreshTokenExpireTime;

    @Autowired
    private AlipayService alipayService;

    @Autowired
    private WalletService walletService;

    @Autowired
    private OrdersService ordersService;

    /**
     * 直接购买商品逻辑
     * @param response
     * @param request
     */
    @GetMapping("/ali")
    public ResponseBean ali(@RequestBody OrderPay orderPay, HttpServletResponse response, HttpServletRequest request) {
        try {
            String email = "ppnjvg1025@sandbox.com";
            String name = "ppnjvg1025";
            String result = alipayService.aliTransfer(orderPay, email, name,response,request);
            return new ResponseBean(HttpStatus.OK.value(), "转账成功", null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseBean(500, "转账失败", null);
    }

//    @PostMapping(value = "/pay")
//    public ResponseBean payment(@RequestBody Map<String, Object> map, HttpServletResponse response, HttpServletRequest request) {
//        String result = null;
//        try {
//            result = alipayService.aliPay(map.get("money").toString(), response, request);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return new ResponseBean(HttpStatus.OK.value(), "跳转中", result);
//    }

    @GetMapping( "/aliFund")
    @ResponseBody
    public void aliFund(OrderPay orderPay, HttpServletResponse response, HttpServletRequest request) {
        try {
            String result = alipayService.aliPay(orderPay, response, request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/wallet")
    public ResponseBean walletPay(@RequestBody WalletPay walletPay){
        WalletDto walletDto = walletService.selectByPrimaryKey(walletPay.getWalletId());
        if(walletDto.getBalance() > walletPay.getMoney()){
            walletDto.setBalance(walletDto.getBalance() - walletPay.getMoney());
            walletService.updateByPrimaryKeySelective(walletDto);
            return new ResponseBean(HttpStatus.OK.value(), "支付成功", null);
        }else {
            return new ResponseBean(HttpStatus.FORBIDDEN.value(), "余额不足", null);
        }
    }

    @RequestMapping("/refund")
    @ResponseBody
    /**
     * @author xujp
     * @Description TODO
     * @param trade_no 支付宝交易号
     * @param refund_amount 退款金额，不能大于这笔订单的钱，可以退部分钱
     * @param response
     * @param request
     * @return void
     * @date 2021/7/11 18:52
     */
    public String payReFund(String trade_no,String refund_amount, HttpServletResponse response, HttpServletRequest request) {
        // 获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key,
                AlipayConfig.sign_type);
        AlipayTradeRefundRequest req = new AlipayTradeRefundRequest();
        // 订单支付时传入的商户订单号,不能和 trade_no同时为空
        // 需要退款的金额
        // 表示支持部分退款
        String out_request_no = System.currentTimeMillis()+"";

        req.setBizContent("{\"trade_no\":\"" + trade_no + "\"," + "\"refund_amount\":\"" + refund_amount + "\","
                + "\"out_request_no\":\"" + out_request_no + "\"}");
        AlipayTradeRefundResponse resp = null;
        try {
            resp = alipayClient.execute(req);
        } catch (AlipayApiException e) {
            return "退款失败";
        }
        if (resp.isSuccess()) {
            return "退款成功";
        } else {
            return "退款失败";
        }

    }

    /**
     * 支付宝同步通知页面,成功返回
     * @param request
     * @param response
     * @param httpSession
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/alipayReturnNotice")
    public String alipayReturnNotice(HttpServletRequest request, HttpServletRequest response, HttpSession httpSession) throws Exception {
        log.info("支付成功, 进入同步通知接口...");
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        log.info("支付宝返回参数："+params);
        // 调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        if(signVerified) {
            //商户订单号
            String orderNo = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);


            Integer orderId = Integer.parseInt(orderNo);
            Orders orders = ordersService.selectByPrimaryKey(orderId);
            if(orders.getOrderType() == '0'){
                orders.setOrderState('1');
            }else {
                orders.setOrderType('7');
            }
            ordersService.updateByPrimaryKeySelective(orders);


            //alipayService.onlyBuy(orderNo);

            log.info("******************** 支付成功(支付宝同步通知) ********************");
            log.info("* 订单号: {}", orderNo);
            log.info("* 支付宝交易号: {}", trade_no);
            log.info("* 实付金额: {}", total_amount);
            log.info("***************************************************************");

        }else{
            log.error("同步回调签名验证失败");
        }
        return "redirect:/index.html";
    }



}
